package com.gongjian.database.service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.gongjian.database.entity.Register;
import com.gongjian.database.entity.User;
import com.gongjian.utile.CodeEntity;
import com.gongjian.utile.Crud;
import com.gongjian.utile.utile.Hump;
import org.apache.ibatis.session.SqlSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

/**
 * @Author: TanLiLin
 * @Date: 2019/3/21 17:16
 * @Version 1.0
 */
@Service
public class RegisterService {
    @Autowired
    SqlSession sqlSession;

    /**
     * 查询所有签到记录
     * @param Page
     * @param PageSize
     * @return
     */
    public String findAllRegister(int Page, int PageSize) {

 //      PageHelper分页插件 传入当前页码和一页显示记录数
        PageHelper.startPage(Page, PageSize);

//      根据分页插件 自行查询出当前页内容
        List<Map<String,Object>> registerList = sqlSession.selectList("findAllRegister");
        registerList= Hump.formatHumpNameForList(registerList);
        CodeEntity codeEntity = new CodeEntity(200,"ok");
        String timeFormat = "yyyy-MM-dd HH:mm:ss";
        JSONArray jsonArray = JSONArray.parseArray(JSONObject.toJSONStringWithDateFormat(registerList,timeFormat));  /**list为 List<Map<String, String>>**/

        codeEntity.setData(jsonArray);

        return codeEntity.toJSONString();

    }

    /**
     * 通过registerId查询一条记录
     * @param registerId
     * @return
     */
    public String findRegisterByRegisterId(int registerId){
        JSONArray registerJSONArray = new JSONArray(sqlSession.selectOne("findRegisterByRegisterId",registerId));
        return  new Crud<JSONArray>().selectNoPage(registerJSONArray);

    }

    /**
     * 通过registerId删除一条记录
     * @param registerIds
     * @return
     */
    public String deleteRegisterByRegisterId(int[] registerIds) {
        for (int i:registerIds){
            sqlSession.update("deleteRegisterByRegisterId", i);
        }
        sqlSession.commit();
        return new CodeEntity(200, "ok").toString();

    }


    /**
     *通过registerId修改一条记录
     * @param
     * @return
     */
    public String updateRegister(Register register){

        sqlSession.selectOne("updateRegister",register);
        sqlSession.commit();
        return new CodeEntity(200,"").toJSONString();
    }


    /**
     * 添加一条记录到register
     * @param register
     * @return
     */
    public String addRegister(Register register){
        int isOk = sqlSession.insert("addRegister",register);
        sqlSession.commit();
        return new Crud<>().isOk(isOk);
    }


}
